package test.redis;
/**
 * @author shench
 * redis数据库管理器
 */
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class DBRedis {
	//****************单例一个连接池***************  
    private static ShardedJedisPool pool = null;
    private ShardedJedis jedis;
    
    public DBRedis(){    	
    	launch();
    }
    
    /**
     * 初始化redis
     */
    private void launch(){
    	get_jedispool();
    	jedis = get_jedis();
    }
    
	 /**         
     * 获取连接池         
     * @return 数据源         
     */       
    public ShardedJedisPool get_jedispool() {  
        if(pool == null){ 
        	ApplicationContext ctx = new FileSystemXmlApplicationContext("testbean.xml");
            pool = (ShardedJedisPool)ctx.getBean("shardedJedisPool");         	
        }  
        return pool;       
    }
    public ShardedJedis get_jedis(){
    	return pool.getResource();
    }
    
    /**
     * 关闭jedis的链接
     */
    public void close(){
    	pool.returnResource(jedis);
    }
    /**
     * 摧毁连接池
     */
    public void destroy(){
    	pool.destroy();
    	
    }
    /**
     * 推进一个数据到key尾中
     * @param key
     * @param strings
     * @return
     */
    public long rpush(String key, String string){
    	return jedis.rpush(key, string);
    }
    public long rpush(String key, String[] strings){
    	return jedis.rpush(key, strings);
    }
    /**
     * 推进一个数据到key头中
     * @param key
     * @param string
     * @return
     */
    public long lpush(String key, String string){
    	return jedis.lpush(key, string);
    }
    public long lpush(String key, String[] strings){
    	return jedis.lpush(key, strings);
    }
    /**
     * 从key尾弹出一个元素
     * @param key
     * @return
     */
    public String rpop(String key){    	
    	return jedis.rpop(key);
    }
    
    /**
     * 查看key是否存在
     * @param key
     * @return
     */
    public boolean exists(String key){
    	return jedis.exists(key);
    }
    
}
